﻿#include "FProgressBar.h"
#include "../Base/FTheme.h"

#include <QPainter>
#include <QPainterPath>

FProgressBar::FProgressBar(QWidget *parent)
    : QProgressBar(parent)
    , m_lightPos(0.0)
{
    setTextVisible(true);
    setFixedHeight(24);

    // 流光动画
    m_lightAnim = new QPropertyAnimation(this, "lightPos", this);
    m_lightAnim->setStartValue(0.0);
    m_lightAnim->setEndValue(1.0);
    m_lightAnim->setDuration(2000);
    m_lightAnim->setLoopCount(-1);
    m_lightAnim->start();
}

void FProgressBar::setLightPos(double pos)
{
    m_lightPos = pos;
    update();
}

void FProgressBar::setLightAnimEnabled(bool en)
{
    m_animEn = en;
}

void FProgressBar::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing, true);

    QRect r = rect();
    int radius = r.height() / 2;

    // 背景
    p.setBrush(FColors::getBaseColor(FColors::Default));
    p.setPen(Qt::NoPen);
    p.drawRoundedRect(r, radius, radius);

    // 进度区域
    double ratio = (double)value() / maximum();
    QRectF progRect = QRectF(r.x(), r.y(), r.width() * ratio, r.height());

    if (ratio > 0) {
        QLinearGradient barGrad(r.topLeft(), r.topRight());
        const auto& linears = FColors::getLinearColors(FColors::Primary, 2);
        barGrad.setColorAt(0, linears[0]);
        barGrad.setColorAt(1, linears[1]);

        // 只填充已经达到的部分
        p.setBrush(barGrad);
        p.setPen(Qt::NoPen);

        p.drawRoundedRect(progRect, radius, radius);

        // 使用圆角裁剪，避免两次绘制产生尖角
        // QPainterPath path;
        // path.addRoundedRect(r, radius, radius);
        // p.setClipPath(path);
        // p.drawRect(progRect);
    }

    // 流光光效
    if (ratio > 0 && m_animEn) {
        double lightWidth = width() * 0.2;
        double startX = progRect.width() * m_lightPos;

        QRectF lightRect(startX - lightWidth/2, r.y(), lightWidth, r.height());

        QLinearGradient glow(lightRect.topLeft(), lightRect.topRight());
        glow.setColorAt(0.0, QColor(255,255,255, 0));
        glow.setColorAt(0.5, QColor(255,255,255, 120)); // 中间亮
        glow.setColorAt(1.0, QColor(255,255,255, 0));

        p.setBrush(glow);
        p.drawRoundedRect(lightRect, radius, radius);
    }

    // 显示百分比文字
    if (isTextVisible()) {
        QString text = QString::number(value()) + "%";
        p.setPen(Qt::black);
        p.setFont(font());
        p.drawText(rect(), Qt::AlignCenter, text);
    }

}
